<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>红绿灯</title>
    <style>
      .lights-box {
        display: flex;
      }
      .light {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        margin: 20px;
        background-color: #ccc;
      }
      .red {
        background-color: #f00;
        filter: brightness(0.5);
      }
      .yellow {
        background-color: #ff0;
        filter: brightness(0.5);
      }
      .green {
        background-color: #0f0;
        filter: brightness(0.5);
      }
      .red.active {
        filter: brightness(1);
      }
      .yellow.active {
        filter: brightness(1);
      }
      .green.active {
        filter: brightness(1);
      }
    </style>
  </head>
  <body>
    <div class="lights-box">
      <div class="light red"></div>
      <div class="light yellow"></div>
      <div class="light green"></div>
    </div>
    <button id="next">next</button>
    <script>
      // 是否自动模式
      var isAuto = false;
      // 时间map
      var timeMap = {
        red: 5,
        yellow: 2,
        green: 10,
      };
      // 自动模式
      function autoLight(type) {
        setLight(type);
        return new Promise((resolve) => {
          setTimeout(resolve, timeMap[type] * 100);
        });
      }
      // 手动模式
      function happen(type, element, eventType) {
        setLight(type);
        return new Promise((resolve) => {
          element.addEventListener(eventType, resolve, { once: true });
        });
      }
      function setLight(type) {
        Array.from(document.querySelectorAll(".light")).forEach((light) => {
          light.classList.remove("active");
        });
        document.querySelector("." + type).classList.add("active");
      }
      
      async function run() {
        if (isAuto) {
          await autoLight("green");
          await autoLight("yellow");
          await autoLight("red");
        } else {
          await happen("green", document.getElementById("next"), "click");
          await happen("yellow", document.getElementById("next"), "click");
          await happen("red", document.getElementById("next"), "click");
        }

        run();
      }
      run();
    </script>
  </body>
</html>
